package com.item.mobile;

import static com.item.mobile.MobileUtil.checkParam;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.base.mobile.MobException;
import com.base.mobile.MobileInfo;
import com.base.mobile.server.annotation.Mobile;
import com.base.mobile.server.annotation.MobileMethod;
import com.item.dao.model.RegisterVerify;
import com.item.dao.model.RegisterVerifyExample;
import com.item.service.RegisterVerifyService;
import com.item.util.ConstantResources;
import com.item.util.ShortMessageSender;
import com.mobile.api.proto.MSystem.MRet;

@Component
@Mobile
public class MAppMobileVerify {
	@Autowired
	private RegisterVerifyService registerVerifyService;
	
	private static String msgSuccess = "验证码已发送";
	
	/**
	 * 获取手机验证码
	 * @Url /mobile?methodno=MGetMobileVerify&debug=1&deviceid=1&phone=15996282157&appid=nju
	 * @param mobileInfo
	 * @param phone
	 * @return
	 * @throws Exception
	 */
	@MobileMethod(methodno = "MGetMobileVerify",isLogin=false,isPage=false)
	public MRet.Builder getMobileVerify(MobileInfo mobileInfo, 
			String phone) throws Exception {
		checkParam(phone, "phone");
		
		MRet.Builder ret = MRet.newBuilder();
		
		//获取该手机号允许重发的时间点
		Date reSendDeadLine = new Date(System.currentTimeMillis() 
				- ConstantResources.VERIFY_INTEVAL);
		
		//检查改手机是否已经注册或正在验证（间隔时间不到60s）		
		RegisterVerifyExample example = new RegisterVerifyExample();
		example.createCriteria().andPhoneEqualTo(phone);
		List<RegisterVerify> list = registerVerifyService.selectByExample(example);
		
		if(list != null && list.size() > 0) {
			RegisterVerify rv = list.get(0);
			if(rv.getSendTime().getTime() > reSendDeadLine.getTime() && rv.getIsV() != 1) {
				if(ShortMessageSender.send(phone, rv.getVerify()) != null) {//未超时，重新发送，不更新超时时间，发送原验证码
					ret.setCode(1);
					ret.setMsg(msgSuccess);
				} else {
					throw new MobException(MEnumError.VERIFYMESSAGE_SEND_ERROR);
				}
			} else {
				//获取随机短信验证码
				String verify = ShortMessageSender.send(phone, null);
				if(verify != null)	{
					rv.setVerify(verify);
					rv.setIsV(0);
					rv.setSendTime(new Date(System.currentTimeMillis()));
					registerVerifyService.updateByPrimaryKeySelective(rv);
					ret.setCode(1);
					ret.setMsg(msgSuccess);
				} else {
					throw new MobException(MEnumError.VERIFYMESSAGE_SEND_ERROR);
				}
			}
		} else {
			//获取随机短信验证码
			String verify = ShortMessageSender.send(phone, null);
			
			if(verify != null) {
				RegisterVerify rv = new RegisterVerify();
				rv.setPhone(phone);
				rv.setSendTime(new Date(System.currentTimeMillis()));
				rv.setVerify(verify);
				rv.setIsV(0);		
				registerVerifyService.insert(rv);
				ret.setCode(1);
				ret.setMsg(msgSuccess);
			} else {
				throw new MobException(MEnumError.VERIFYMESSAGE_SEND_ERROR);
			}
		}
		
		return ret;
	}

}
